package com.google.ant.extensions.tasks;

import java.io.File;
import com.google.ant.extensions.types.Module;

public class InstallTask extends AbstractFantTask {

    public static final String PROJECT_GROUP_ID = "project.group.id";
    public static final String PROJECT_ARTIFACT_ID = "project.artifact.id";
    public static final String PROJECT_VERSION = "project.version";
    private static final String PROJECT_DIST_DIR = "dist.dir";

    File artifact;
    String revision;

    public void setRevision(String revision) {
		this.revision = revision;
        System.out.println("revision:"+revision);
	}

	public void execute() {
        String groupId = getProject().getProperty(PROJECT_GROUP_ID);
        if (groupId != null) {
            groupId = groupId.replace(".", "/");
        }
        String artifactId = getProject().getProperty(PROJECT_ARTIFACT_ID);
        String version = revision;
        System.out.println("version:"+version);
        if(version == null){
        	version = getProject().getProperty(PROJECT_VERSION);
        }

        if (destdir == null) {
            String relativePath = groupId + File.separator + artifactId + File.separator + version;
            destdir = new File(localRepository, relativePath);

            mkdirTask.setDir(destdir);
            mkdirTask.execute();
        }

        String artifactName = artifactId + "-" + version + ".jar";
        if (artifact == null) {
            String distDir = getProject().getProperty(PROJECT_DIST_DIR);
            if (distDir == null) {
                distDir = getProject().getBaseDir().toString();
            }
			artifact = new File(distDir, artifactName);
        }

        copy(artifact, destdir, true);
        System.err.println("\n\n Installed " + artifact + " into " + destdir + " \n");

        registerSource();
        System.out.println("publish " + artifactName + " Successfully.");
    }

    private void registerSource() {
        Module module = new Module();
        module.setModuleProject(getProject());
        module.selfRegister();
    }
}
